package com.cnzhy.tomcat;

import com.cnzhy.servlet.Servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

public class MyTomcat {

    private static final int port = 18080;
    private static final Properties properties = new Properties();
    public static final HashMap<String, Servlet> servletMapping = new HashMap<>();

    public static void main(String[] args) throws Exception {
        MyTomcat myTomcat = new MyTomcat();
        myTomcat.init();
        myTomcat.start();
    }

    private void init() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        String basePath = URLDecoder.decode(MyTomcat.class.getResource("/").getPath(), "UTF-8");
        try (InputStream io = new FileInputStream(basePath + "web.properties")) {
            // 获取basePath
            properties.load(io);
            // 初始化ServletMapping
            // 返回属性key的集合
            Set<Object> keys = properties.keySet();
            for (Object key : keys) {
                if (key.toString().contains("url")) {
                    System.out.println(key.toString() + "=" + properties.get(key));
                    // 根据key值获取className
                    Object classname = properties.get(key.toString().replace("url", "classname"));
                    servletMapping.put(properties.get(key.toString()).toString(), (Servlet) Class.forName(classname.toString()).newInstance());
                }
            }
        }
    }

    private void start() {
        try(ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Tomcat 服务已启动，地址：localhost ,端口：" + port);
            // 持续监听
            do {
                Socket socket = serverSocket.accept();
                System.out.println(socket);
                // 处理任务
                Thread thread = new SocketProcess(socket);
                thread.start();
            } while (true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
